package com.rdc.qingkou.view.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.adapter.TwoLevelCommentRecyclerViewAdapter;
import com.rdc.qingkou.presenter.TwoLevelCommentPresenter;
import com.rdc.qingkou.ui.CommentActivity;
import com.rdc.qingkou.ui.iview.ITwoLevelCommentView;
import com.rdc.qingkou.utils.MyUtils;
import com.rdc.qingkou.vo.CommentTwoLevelVO;

import java.util.ArrayList;
import java.util.List;


public class TwoLevelCommentFragment extends Fragment implements ITwoLevelCommentView {
    private TwoLevelCommentRecyclerViewAdapter mAdapter;
    public EditText editText;
    private CommentActivity mActivity;
    private SwipeRefreshLayout mSwipeRefresh;

    private List<CommentTwoLevelVO> mRecentCommentList = new ArrayList<>();
    public TwoLevelCommentPresenter presenter;
    private int mParentCommentId;//一级评论id
    private int mCurrentPage = 1;
    private boolean isLastPage = false;//是否是最后一页
    private boolean isUpdate = false;//是否正在加载
    private int mLastPageCommentNum = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (CommentActivity) getContext();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mParentCommentId = savedInstanceState.getInt("id");
        }
        mActivity.isOneLevelComment = false;
        mActivity.title.setText("评论列表");
        presenter = new TwoLevelCommentPresenter();
        presenter.attachView(this);
        View view = inflater.inflate(R.layout.fragment_comment, container, false);
        initViews(view);
        refresh();
        return view;
    }

    private void initViews(final View view) {
        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.comment_swipeRefreshLayout);
        mSwipeRefresh.setColorSchemeResources(R.color.colorStart);
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        editText = (EditText) view.findViewById(R.id.comment_input_editText);

        ImageButton mSendImageButton = (ImageButton) view.findViewById(R.id.comment_send_imageButton);
        mSendImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(editText.getText())) {
                    String hint = "";
                    if (editText.getHint() != null) {
                        hint = editText.getHint().toString();
                        hint = hint.substring(2, hint.length() - 1);
                    }
                    presenter.sendTwoLevelComment(
                            editText.getText().toString(),
                            MyApplication.getUser().getUserId(),
                            mAdapter.getReviewerId(),
                            mParentCommentId,
                            hint);
                    //清除用户输入并且收起键盘
                    editText.getText().clear();
                    MyUtils.hideKeyboard(mActivity);
                    editText.clearFocus();
                    editText.setHint(null);
                    mAdapter.setReviewerId(0);
                }
            }
        });

        final RecyclerView commentRecyclerView = (RecyclerView) view.findViewById(R.id.commit_recyclerView);
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        commentRecyclerView.setLayoutManager(layoutManager);

        mAdapter =
                new TwoLevelCommentRecyclerViewAdapter(
                        mActivity,
                        this,
                        mRecentCommentList);
        commentRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!commentRecyclerView.canScrollVertically(1) && !isLastPage && !isUpdate) {
                    //发起网络请求获取数据
                    isUpdate = true;
                    presenter.getTwoLevelComment(mParentCommentId, mCurrentPage);
                } else if (!commentRecyclerView.canScrollVertically(1) && isLastPage) {
                    Toast.makeText(mActivity, "没有更多评论了！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("id", mParentCommentId);
    }

    public void setParentCommentId(int id) {
        mParentCommentId = id;
    }

    private void refresh() {
        if (MyUtils.isNetworkConnected(mActivity)) {
            isUpdate = true;
            isLastPage = false;
            mSwipeRefresh.setRefreshing(true);
            presenter.getTwoLevelComment(mParentCommentId, 1);
        } else {
            Toast.makeText(mActivity, "无网络！", Toast.LENGTH_SHORT).show();
            mSwipeRefresh.setRefreshing(false);
        }
    }

    @Override
    public void onDestroyView() {
        presenter.detachView();
        presenter.clearDisposable();
        super.onDestroyView();
    }

    @Override
    public void appreciateError(String message) {
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void appreciateSuccess(int id, boolean flag) {
        for (int i = 0; i < mRecentCommentList.size(); i++) {
            if (mRecentCommentList.get(i).getCommentId() == id) {
                CommentTwoLevelVO commentTwoLevelVO = mRecentCommentList.get(i);
                if (commentTwoLevelVO.getCommentId() == id) {
                    if (flag) {
                        commentTwoLevelVO.setPraiseNumber(commentTwoLevelVO.getPraiseNumber() + 1);
                    } else {
                        commentTwoLevelVO.setPraiseNumber(commentTwoLevelVO.getPraiseNumber() - 1);
                    }
                    commentTwoLevelVO.setPraise(flag);
                    mAdapter.notifyDataSetChanged();
                    return;
                }
            }
        }
    }

    @Override
    public void getTwoLevelCommentsSuccess(List<CommentTwoLevelVO> recentComments) {
        if (mSwipeRefresh.isRefreshing()) {
            //下拉刷新全部重新加载
            mRecentCommentList.clear();
            if (recentComments.size() < 15) {
                isLastPage = true;
                mCurrentPage = 1;
                mLastPageCommentNum = recentComments.size();
            } else {
                mCurrentPage = 2;
            }
        } else {
            //上拉
            if (recentComments.size() < 15) {
                isLastPage = true;
                mLastPageCommentNum = recentComments.size();
            } else {
                mCurrentPage++;
            }
        }
        mRecentCommentList.addAll(recentComments);
        mAdapter.notifyDataSetChanged();
        isUpdate = false;
        mSwipeRefresh.setRefreshing(false);
    }

    @Override
    public void getTwoLevelCommentsError(String message) {
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
        isUpdate = false;
        mSwipeRefresh.setRefreshing(false);
    }

    @Override
    public void sendTwoLevelCommentsError(String message) {
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void sendTwoLevelCommentsSuccess(CommentTwoLevelVO c) {
        Toast.makeText(mActivity, "发送评论成功！", Toast.LENGTH_SHORT).show();
        if (mCurrentPage == 1) {
            refresh();
        } else if (isLastPage) {
            while (mLastPageCommentNum != 0) {
                mRecentCommentList.remove(mRecentCommentList.size() - 1);
                mLastPageCommentNum--;
            }
            presenter.getTwoLevelComment(mParentCommentId, mCurrentPage);
            isUpdate = true;
        }
    }
}
